package com.yizhubao.app.activitys.user;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.yizhubao.app.MainActivity;
import com.yizhubao.app.R;
import com.yizhubao.app.activitys.RecordDetailActivity;
import com.yizhubao.app.activitys.WebActivity;
import com.yizhubao.app.activitys.release.ReleaseActivity;
import com.yizhubao.app.adapters.ExchangeImageAdapter;
import com.yizhubao.app.adapters.ExchangeUserAdapter;
import com.yizhubao.app.adapters.ReleaseImageAdapter;
import com.yizhubao.app.adapters.ReleaseUserAdapter;
import com.yizhubao.app.base.BaseActivityToolBar;
import com.yizhubao.app.base.BaseResultBean;
import com.yizhubao.app.beans.RecordBean;
import com.yizhubao.app.beans.RecordDetailBean;
import com.yizhubao.app.beans.SelectImageBean;
import com.yizhubao.app.customviews.BottomDialog;
import com.yizhubao.app.events.RecordEvent;
import com.yizhubao.app.models.RecordDetailModel;
import com.yizhubao.app.presenters.SaveRecordPresenter;
import com.yizhubao.app.utils.Constants;
import com.yizhubao.app.utils.GlideEngine;
import com.yizhubao.app.utils.Utils;
import com.yizhubao.app.utils.net.BaseObserver;
import com.yizhubao.app.views.SaveRecordView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import h.framework.pacy.utils.JsonUtil;
import h.framework.pacy.utils.LogUtil;
import h.framework.pacy.utils.PreferencesUtil;
import h.framework.pacy.utils.ScreenUtil;
import h.framework.pacy.utils.StringUtil;
import h.framework.pacy.utils.ToastUtil;
import h.framework.pacy.views.recyclerview.DividerDecoration;

/**
 * 创建人: PACY
 * 创建时间: 6/6/21 10:25 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: 修改页面
 */
public class ExchangeActivity extends BaseActivityToolBar implements SaveRecordView {
    RecordDetailModel recordDetailModel;
    private String recordId;


    @BindView(R.id.base_left_icon)
    ImageView leftIcon_iv;
    //图片选择
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.image_rv)
    RecyclerView image_rv;
    ExchangeImageAdapter adapter;
    GridLayoutManager layoutManager;

    //联系人
    @BindView(R.id.user_rv)
    RecyclerView user_rv;
    ExchangeUserAdapter userAdapter;
    LinearLayoutManager linearLayoutManager;

    private OSS oss;

    private RecordDetailBean recordBean;
    @BindView(R.id.content_tv)
    EditText content_tv;//内容
    SaveRecordPresenter recordPresenter;

    @Override
    protected int setContentLayout() {
        return R.layout.activity_release;
    }

    @Override
    protected void initView() {
        setTitleOnLeftIcon(R.drawable.icon_back,"");
        initImagePicker();
        initUserList();
        EasyPhotos.preLoad(ExchangeActivity.this);
        leftIcon_iv.setOnClickListener(v -> {
            BottomDialog.DialogBuilder(ExchangeActivity.this)
                    .title("内容还没保存!")
                    .message("离开后，刚才编辑的内容会被清除掉。请继续完成内容的填写，然后保存。")
                    .completeText("继续填写")
                    .completeCallBack(() -> {

                    }).cancleText("离开")
                    .othersCallBack(this::onBackPressed)
                    .show();
        });
    }

    @Override
    protected void initData() {
        recordId=getIntent().getExtras().getString("recordId");
        recordDetailModel=new RecordDetailModel();
        sendDetailRequest();

        recordPresenter = new SaveRecordPresenter();
        recordPresenter.attachView(this);

        initOss();
    }


    /**
     * 初始化阿里云OSS
     */
    private void initOss() {
        //云OSS初始化配置
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(Constants.accessKeyId, Constants.accessKeySecret);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), Constants.endpoint, credentialProvider, conf);
    }


    private void sendRequest() {
        String content = content_tv.getText().toString();
        recordBean.getAssignorList().clear();
        recordBean.getAssignorList().addAll(userAdapter.getData());
        recordBean.setUserId(Long.parseLong(Utils.getUserId()));
        recordBean.setContent(content);
        recordBean.setType(1);
        LogUtil.i(recordBean.toString());

        if (StringUtil.isEmpty(content) && recordBean.getUrlList().isEmpty()) {
            ToastUtil.showShort("请先输入内容");
            return;
        }

        if (recordBean.getAssignorList().isEmpty()) {
            ToastUtil.showShort("联系人异常，请仔细检查");
            return;
        }

        boolean bol=true;
        for(RecordDetailBean.AssignorListBean s:recordBean.getAssignorList()){
            if(StringUtil.isEmpty(s.getName())||StringUtil.isEmpty(s.getPhone())){
                bol=false;
            }
        }
        if(!bol){
            ToastUtil.showShort("联系人异常，请仔细检查");
            return;
        }


        if(recordBean.getUrlList().get(recordBean.getUrlList().size()-1).isAdd()){
            recordBean.getUrlList().remove(recordBean.getUrlList().size()-1);
        }
        Map<String, Object> map = new HashMap<>();
        map = JsonUtil.jsonToMap(JsonUtil.objectToJson(recordBean));
        recordPresenter.sendListRequest(map);
    }



    /**
     * 请求保存
     */
    private void uploadImage(List<SelectImageBean> urls) {
        showLoading("请稍候");
        ossUpload(urls);
    }

    /**
     * 递归的方式上传图片
     *
     * @param urls
     */
    private void ossUpload(List<SelectImageBean> urls) {
        if (urls.size() <= 0) {
            // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThead做对应逻辑
            runOnUiThread(() -> {
                LogUtil.i("全部上传完成");
                dismissDialog();
                setImageUI();
            });
            return;
        }

        final String temp = Utils.getUUID(urls.get(0).getType());

        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(Constants.testBucket, Constants.uploadObject + temp, urls.get(0).getImageUrl());

        // 异步上传时可以设置进度回调
        put.setProgressCallback((request, currentSize, totalSize) -> LogUtil.i("currentSize: " + currentSize + " totalSize: " + totalSize));

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtil.i(result.getETag());
                LogUtil.i(result.getRequestId() + "-----" + result.getResponseHeader().toString());
                LogUtil.i("上传成功---");
                RecordDetailBean.UrlListBean dto = new  RecordDetailBean.UrlListBean();
                dto.setType(urls.get(0).getType());
                dto.setUrl(Constants.ossImagePath + temp);
                recordBean.getUrlList().add(recordBean.getUrlList().size()-1,dto);
                urls.remove(0);
                ossUpload(urls);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常

                    LogUtil.e("ErrorCode=" + serviceException.getErrorCode() + "\nRawMessage=" + serviceException.getRawMessage());
                }
                runOnUiThread(() -> {
                });
            }
        });
    }


    /**
     * 设置图片选择的UI
     */
    private void setImageUI() {
        if (recordBean.getUrlList().size() > 9) {
            recordBean.getUrlList().remove(recordBean.getUrlList().size() - 1);
        } else {
            if (!recordBean.getUrlList().get(recordBean.getUrlList().size() - 1).isAdd()) {
                recordBean.getUrlList().add(recordBean.getUrlList().size(), new  RecordDetailBean.UrlListBean(true));
            }
        }
        adapter.setNewData(recordBean.getUrlList());
    }

    /**
     * 点击事件
     */
    @OnClick(value = {R.id.addUser_tv, R.id.weituo_lin, R.id.commit_tv})
    public void click(View v) {
        if (v.getId() == R.id.addUser_tv) {
            if(userAdapter.getItemCount()<5){
                userAdapter.addData(new RecordDetailBean.AssignorListBean("",""));
            }else{
                ToastUtil.showShort("联系人最多添加5个");
            }

        } else if (v.getId() == R.id.weituo_lin) {
            BottomDialog.DialogBuilder(ExchangeActivity.this)
                    .title("联系人")
                    .message("①只有在确认您已经发生意外后，平台才会第一时间，将内容转交给以下所有联系人。②若没发生意外，联系人不会看到您记录的任何内容。③最少一个，最多可添加五个联系人。")
                    .completeCallBack(() -> {

                    }).completeText("知道了").othersCallBack(() -> {
                Bundle bundle = new Bundle();
                bundle.putString("title", "如何使用");
                bundle.putString("url", Constants.QUESTION);
                startActivity(ExchangeActivity.this, WebActivity.class, bundle);
            }).cancleText("了解更多")
                    .show();
        } else if (v.getId() == R.id.commit_tv) {
            sendRequest();
        }
    }

    /**
     * 初始化联系人列表
     */
    private void initUserList() {
        userAdapter = new ExchangeUserAdapter();
        linearLayoutManager = new LinearLayoutManager(ExchangeActivity.this);
        user_rv.setAdapter(userAdapter);
        user_rv.setLayoutManager(linearLayoutManager);

        userAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.userDelete_tv) {
                    userAdapter.remove(position);
                }
            }
        });
    }

    /**
     * 初始化图片选择列表
     */
    private void initImagePicker() {
        adapter = new ExchangeImageAdapter();
        image_rv.setAdapter(adapter);
        layoutManager = new GridLayoutManager(ExchangeActivity.this, 3);
        image_rv.setLayoutManager(layoutManager);
        //添加分割线
        DividerDecoration decoration = new DividerDecoration(getResources().getColor(R.color.transparent), ScreenUtil.dp2px(10));
        image_rv.addItemDecoration(decoration);

        adapter.setOnItemChildClickListener((ad, view, position) -> {
            if (view.getId() == R.id.delete_iv) {
                adapter.remove(position);
                if (!adapter.getItem(adapter.getItemCount() - 1).isAdd()) {
                    adapter.addData(adapter.getItemCount(), new RecordDetailBean.UrlListBean(true));
                }
            } else if (view.getId() == R.id.select_lin) {
                selectImage();
            } else if (view.getId() == R.id.image_rel) {
            }
        });
    }

    /**
     * 选择图片
     */
    private void selectImage() {
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                .setFileProviderAuthority("com.yizhubao.app.fileprovider")//参数说明：见下方`FileProvider的配置`
                .setCount(10-adapter.getItemCount())//参数说明：最大可选数，默认1
                .setPuzzleMenu(false)
                .setVideo(true)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        LogUtil.i("size==" + photos.size());
                        List<SelectImageBean> urls = new ArrayList<>();
                        for (Photo p : photos) {
                            if (p.type.equals("image/jpeg")||p.type.equals("image/png")) {
                                urls.add(new SelectImageBean(p.path, false, 1));
                            } else {
                                urls.add(new SelectImageBean(p.path, false, 2));
                            }
                        }
                        uploadImage(urls);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Override
    public void onSaveSuccess(boolean success) {
        if (success) {
            ToastUtil.showShort("保存成功!");
            EventBus.getDefault().post(new RecordEvent());
            startActivity(ExchangeActivity.this, MainActivity.class);
            finish();
        }
    }


    /**
     * 获取详情
     */
    private void sendDetailRequest(){
        showLoading();
        Map<String,Object> map=new HashMap<>();
        map.put("recordId",recordId);
        recordDetailModel.getRecordDetail(map, new BaseObserver<RecordDetailBean>() {
            @Override
            public void onSuccess(BaseResultBean<RecordDetailBean> t) {
                //有草稿
                recordBean= t.getData();
                content_tv.setText(recordBean.getContent());
                if(recordBean.getUrlList().size()<9){
                    recordBean.getUrlList().add(recordBean.getUrlList().size(), new RecordDetailBean.UrlListBean(true));
                }
                adapter.setNewData(recordBean.getUrlList());
                userAdapter.addData(recordBean.getAssignorList());
            }

            @Override
            public void onError(String errMessage) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                dismissDialog();
            }
        },getLifeSubject());
    }
}